package com.car.serivce.integration;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.beans.StringBean;
import org.htmlparser.filters.AndFilter;
import org.htmlparser.filters.HasAttributeFilter;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.lexer.StringSource;
import org.htmlparser.tags.TableColumn;
import org.htmlparser.tags.TableRow;
import org.htmlparser.tags.TableTag;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;
import org.htmlparser.util.ParserUtils;
import org.htmlparser.util.SimpleNodeIterator;

import com.car.spdier.HashTable;
import com.car.spdier.service.dao.entity.Punishment;
import com.spider.web.url.MyHttpClient;
/**
 * @deprecated
 * @author Administrator
 *
 */ 
public class SShangHaiHttpClient {
	public static String shanghai = "http://www.shjtaq.com/zwfg/dzjc_new.asp";
	public static String carNoKEY = "carnumber";
	public static String cityKey = "cardqz";
	public static String type = "type1";
	public static String charset = "gb2312";
	public static String act = "search";

	/**
	 * @deprecated
	 * @param map
	 * @return
	 */
	public static List<Map> queryViolationByCity(Map map) {
		try {
			MyHttpClient.getPostMethod(shanghai, map, charset);
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			System.out.print(e1.getStackTrace());
		}
		List queryDetails = new ArrayList();
		String[] textname = new String[] { carNoKEY, cityKey, type, act };
		String[] params = new String[] { map.get("carNo").toString(),
				map.get("city").toString(), map.get("type").toString(),
				map.get("act").toString() };
		try {
			PostMethod postMethod = MyHttpClient.getPostMethod(shanghai,
					textname, params, charset);
			postMethod.getAuthenticationRealm();
			//div align="center" class="chinses1"
			//System.out.println( postMethod.getResponseBodyAsString());
			String rsStr = postMethod.getResponseBodyAsString();
			String str = getTag("(<div)(.*)class=*chinses1*[\"\'](.*)(/>)",
					rsStr);
			System.out.println(str);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// TODO Auto-generated method stub
		return queryDetails;
	}

	public static void main(String[] args) throws ParserException {/*
		 Parser httpParser = new Parser("c://1map.html");
		 httpParser.setEncoding("GB2312");
		//Parser httpParser =Parser.createParser(htmlSourceCode, HashTable.getCharset(HashTable.shanghaiUrlKey).toString());
		NodeFilter filter_tables = new AndFilter((new TagNameFilter("table")),
				new HasAttributeFilter("bgcolor", "#6B654D"));
		NodeList nodeTables = null;
		try {
			nodeTables = httpParser.parse(filter_tables);
		} catch (ParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		Node tableOne = nodeTables.elementAt(0);
		String constellation = tableOne.getFirstChild().getNextSibling()
				.toHtml();

		Node tableTwo = nodeTables.elementAt(1);
		NodeList tableTwo_nodelist = tableTwo.getChildren();
		Node tableThree = nodeTables.elementAt(2);
		if (tableThree instanceof TableTag) {
			TableTag tableTag = (TableTag) tableThree;
			 List<Punishment> listRS=new SShangHaiHttpClient().parserTable(tableTag);
			 stroeDb(listRS);
		}

		NodeList tableThree_nodelist = tableThree.getChildren();
		SimpleNodeIterator nodeItes = tableThree_nodelist.elements();
		while (nodeItes.hasMoreNodes()) {
			Node node = nodeItes.nextNode();

		}

		//System.out.println(tableThree.toHtml());//找到了需要的table 
		// TODO Auto-generated method stub
	*/}
	
	
    private static void stroeDb(List<Punishment> listResult){
    	
    	for(Punishment rs:listResult){
    		System.out.println( rs.toString());
    	}
    	
    }
	private static String getTag(String pattern, String str) {
		Pattern sp = Pattern.compile(pattern);
		Matcher matcher = sp.matcher(str);
		while (matcher.find()) {
			for (int i = 0; i < matcher.groupCount(); i++) {
				System.out.println("  html 正则表达式解析 " + matcher.group(i));
				;
			}
		}
		return "";
	}

	private  List<Punishment> parserTable(TableTag tableTag) {
        List<Punishment> listRS=new ArrayList();
		tableTag.getChildrenHTML();
		SimpleNodeIterator nodes = tableTag.elements();
		Punishment prs = new Punishment();
		while (nodes.hasMoreNodes()) {
			Node node = nodes.nextNode();
			if (node instanceof TableRow) {
				TableRow row = (TableRow) node;
				System.out.println("--TableRow--处理开始---");

				SimpleNodeIterator colNodes = row.elements();
				while (colNodes.hasMoreNodes()) {
					Node colNode = colNodes.nextNode();
					if (colNode instanceof TableColumn) {
						TableColumn col = (TableColumn) colNode;
						String colText = ParserUtils.trimAllTags(col
								.getChildrenHTML(), false);
						colText = ParserUtils.removeEscapeCharacters(colText);
						colText = ParserUtils.removeTrailingBlanks(colText);
						colText = ParserUtils.removeChars(colText, ' ');
						if(prs.isFull()){
							listRS.add(prs);
							prs= new Punishment();
						}
						prs.setValue(colText);
					    preprocePunishment(  prs,   colText);

					}
				}
				System.out.println("--TableRow--处理结束---");
			}

		}
		return listRS;

	}
    /**
     * 上海违章查询字段处理
     * @param prs
     * @param colString
     */
	public void preprocePunishment(Punishment prs, String colString) {
		if (colString.startsWith("违法时间：")) {
			System.out.println(colString);
			prs.isRSDate = true;
			return;
		}
		if (colString.startsWith("编号：")) {
			System.out.println(colString);
			prs.isRS_code = true;
			return;
		}
		if (colString.startsWith("执法机关代码")) {
			System.out.println(colString);
			prs.isOrg_code = true;
			return;
		}
		if (colString.startsWith("违法地点：")) {
			System.out.println(colString);
			prs.isSpace = true;
			return;
		}
		if (colString.startsWith("采集机关：")) {
			System.out.println(colString);
			prs.isOrg_name = true;
			return;
		}
		if (colString.startsWith("违法内容：")) {
			System.out.println(colString);
			prs.isContent= true;
			return;
		}
		if (colString.startsWith("违反条款：")) {
			System.out.println(colString);
			prs.isClause= true;
			return;
		}
		if (colString.startsWith("处罚依据：")) {
			System.out.println(colString);
			prs.isAccord= true;
			return;
		}
		if (colString.startsWith("处罚内容：")) {
			System.out.println(colString);
			prs.isPunishment= true;
			return;
		}
		if (colString.startsWith("其他措施：")) {
			System.out.println(colString);
			prs.isPunishment= true;
			return;
		}

	}

	/**
	 *  
	 * @param tableTag
	 * @return
	 * @deprecated
	 */
	private static Map parserTable2(TableTag tableTag) {

		tableTag.getChildrenHTML();
		SimpleNodeIterator nodes = tableTag.elements();
		while (nodes.hasMoreNodes()) {
			Node node = nodes.nextNode();
			if (node instanceof TableRow) {
				TableRow row = (TableRow) node;
				System.out.println("--TableRow--处理开始---");
				SimpleNodeIterator colNodes = row.elements();
				while (colNodes.hasMoreNodes()) {
					Node colNode = colNodes.nextNode();
					if (colNode instanceof TableColumn) {
						TableColumn col = (TableColumn) colNode;
						String colText = ParserUtils.trimAllTags(col
								.getChildrenHTML(), false);
						colText = ParserUtils.removeEscapeCharacters(colText);
						colText = ParserUtils.removeTrailingBlanks(colText);
						if (colText.matches("违法时间")) {
							System.out.println(colText
									+ "===================================");
						}
						System.out.println(ParserUtils.trimAllTags(col
								.getChildrenHTML(), false));

						/*System.out.println(ParserUtils.trimAllTags(col
								.getChildrenHTML(), true));
						System.out.println("--TableColumn--处理结束---");*/
						/*	try {									 
								Parser parser=ParserUtils.createParserParsingAnInputString(col.getChildrenHTML());
								
							} catch (UnsupportedEncodingException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							
							StringSource src=new StringSource(col.getChildrenHTML());
							src.toString();
							 StringBean sb = new StringBean ();
							 
						        sb.setLinks (false);
						        sb.setReplaceNonBreakingSpaces (true);
						        sb.setCollapse (true);
						        sb.setURL (args[0]);
						        System.out.println (sb.getStrings ());*/
					}
				}
				System.out.println("--TableRow--处理结束---");
			}

		}
		return null;

	}

}
